package com.king.headline.fragment;

/**
 * Created by king on 2015/12/1.
 */

import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.king.headline.R;
import com.king.headline.adapter.MainAdapter;
import com.king.headline.base.BaseFragment;
import com.king.headline.beans.BannerInfos;
import com.king.headline.beans.MainInfo;
import com.king.headline.beans.UserInfo;
import com.king.headline.cache.CacheUtils;
import com.king.headline.net.Callback;
import com.king.headline.net.NetWork;
import com.king.headline.util.AccountManager;
import com.king.headline.util.Configuration;
import com.king.headline.util.CustomToast;
import com.king.headline.util.LoadingUtils;
import com.king.headline.util.UIUtils;
import com.king.headline.util.Utils;
import com.king.headline.view.viewPager.AutoScrollViewPager;
import com.king.headline.view.viewPager.ItemInfo;
import com.king.headline.view.viewPager.OnMyClickListener;
import com.king.headline.view.viewPager.PicPagerAdapter;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class OneFragment extends BaseFragment {
    private PullToRefreshListView mRlListView;
    private ListView lv_main;
    private AutoScrollViewPager viewPager;


    private LoadingUtils loadingUtils;
    private static final String TAG_CONTENT_FRAGMENT = "TAG_CONTENT_FRAGMENT";
    private boolean isRefresh;
    private boolean isLoadMore;
    private int index;
    private  ArrayList<MainInfo> mainInfoListAll = new ArrayList<MainInfo>();
    private MainAdapter adapter;
    private String encyptdId;
    private String apikey;
    private CacheUtils cacheUtils;
    private boolean toClearn;

    @Override
    public View initView() {
        loadingUtils = new LoadingUtils(mActivity) {
            @Override
            public void right_click() {
            }
        };
        cacheUtils = new CacheUtils();
        View view = View.inflate(mActivity, R.layout.activity_one, null);
        mRlListView = (PullToRefreshListView) view.findViewById(R.id.lv_main);
        lv_main = mRlListView.getRefreshableView();
        viewPager = new AutoScrollViewPager(mActivity);
        viewPager.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, (int) (Utils.getScreenWidth()*0.5)));
        lv_main.addHeaderView(viewPager);

        mRlListView.setMode(PullToRefreshBase.Mode.BOTH);
        mRlListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                isRefresh = true;
                mainInfoListAll.clear();
                index = 0;// 页面重置
                getBannerFromNet();
                getMainFromNet();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                isLoadMore = true;
                if (mainInfoListAll != null && mainInfoListAll.size() > 0) {
                    index = mainInfoListAll.get(mainInfoListAll.size() - 1).index_;
                }
                getMainFromNet();
            }

        });
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void initData() {
        UserInfo userInfo = AccountManager.getInstance().getUser();
        if (userInfo!=null){
            encyptdId = userInfo.encyptdId;
            apikey =   userInfo.apikey;
        }
        getCacheFromNet();
        toClearn = true;
        getBannerFromNet();
        getMainFromNet();
    }


    private void getCacheFromNet(){
        String cacheMainStr = cacheUtils.getString(CacheUtils.CacheAppMain, "");
        if (!TextUtils.isEmpty(cacheMainStr)) {
            setAppMain(cacheMainStr);
        }
    }
    public void getMainFromNet() {

        NetWork.getInstance().getMain(encyptdId, apikey, index, new Callback() {
            @Override
            public void success(String result) {
                RefreshComplete();
                setAppMain(result);
                cacheUtils.putString(CacheUtils.CacheAppMain, result);//缓存数据
            }

            @Override
            public void notice(JSONObject jsonObject, String message) {
                RefreshComplete();
                CustomToast.showToast(message);
            }

            @Override
            public void failed(String e) {
                RefreshComplete();
                CustomToast.showToast(e);
            }
        });

    }

private void setAppMain(String result){
    ArrayList<MainInfo> mainInfoList = new Gson().fromJson(
            result,
            new TypeToken<List<MainInfo>>() {
            }.getType());
    if (mainInfoList == null || mainInfoList.size() == 0) {
        CustomToast.showToast("没有更多数据了");
    } else {
        if(toClearn){
            mainInfoListAll.clear();
            toClearn = false;
        }

        mainInfoListAll.addAll(mainInfoList);
        if (adapter == null) {
            adapter = new MainAdapter(mActivity, mainInfoListAll);
            lv_main.setAdapter(adapter);
        } else {
            adapter.setDate(mainInfoListAll);
        }
    }
}
    private void getBannerFromNet() {
        String CacheBanner = cacheUtils.getString(CacheUtils.CacheBanner, "");
        if (!TextUtils.isEmpty(CacheBanner)) {
            setBanner(CacheBanner);
        }
        NetWork.getInstance().getBanner(encyptdId, apikey, new Callback() {

            @Override
            public void success(String result) {
                //设置banner信息
                setBanner(result);

                cacheUtils.putString(CacheUtils.CacheBanner, result);//缓存数据
            }

            @Override
            public void notice(JSONObject jsonObject, String message) {
                CustomToast.showToast(message);
            }

            @Override
            public void failed(String e) {
                CustomToast.showToast(e);
            }
        });

    }

    /**
     * 设置banner的信息
     */
    private void setBanner(String result) {
        BannerInfos bannerInfos = new Gson().fromJson(result, BannerInfos.class);
        ArrayList<ItemInfo> imageIdList = new ArrayList<ItemInfo>();
        for (int i = 0; i < bannerInfos.bannerList.size(); i++) {
            ItemInfo itemInfo = new ItemInfo();
            itemInfo.str = Configuration.API_HOST + bannerInfos.bannerList.get(i).img;
            itemInfo.object = bannerInfos.bannerList.get(i);
            imageIdList.add(itemInfo);
        }
        viewPager.setAdapter(new PicPagerAdapter(mActivity, imageIdList, new OnMyClickListener() {
            @Override
            public void myClick(View v) {
                ItemInfo itemInfo = (ItemInfo) v.getTag();
                BannerInfos.BannerInfo bannerInfo = (BannerInfos.BannerInfo) itemInfo.object;
                if (bannerInfo!=null){
                    switch (bannerInfo.type){
                        case "1"://网页
                            UIUtils.goAnyActivity(bannerInfo.data, "com.king.headline.UI.webview.WebViewActivity");
                            break;
                        case "2"://详情
                            UIUtils.goAnyActivity(bannerInfo.data, "com.king.headline.UI.DetailActivity");
                            break;
                    }
                }
            }
        }));
        viewPager.setInterval(5000);
        viewPager.setStopScrollWhenTouch(true);
        viewPager.startAutoScroll();
        if(imageIdList!=null && imageIdList.size()>0){
            viewPager.setVisibility(View.VISIBLE);
            viewPager.setCurrentItem(1000 / 2 - 1000 / 2 % imageIdList.size());
        }else{
            viewPager.setVisibility(View.GONE);
            CustomToast.showToast("xxxx");
        }

    }


    private void RefreshComplete(){
        if (mRlListView != null) {
            mRlListView.onRefreshComplete();
        }
        isRefresh=false;
        isLoadMore=false;
    }

}

